package com.ccteam.fluidmusic.ui.dialog

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.ccteam.fluidmusic.NavAlbumDirections
import com.ccteam.fluidmusic.NavArtistDirections
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.DialogMusicMoreBinding
import com.ccteam.fluidmusic.fluidmusic.common.utils.MediaIDHelper
import com.ccteam.fluidmusic.view.bean.MoreInfoData
import com.ccteam.fluidmusic.widget.SNACKBAR_ALL_BOTTOM_BAR
import com.ccteam.fluidmusic.widget.snackbar
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.fluidmusic.ui.moment.AddMomentActivity
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_MUSIC
import com.ccteam.shared.result.moment.MomentListItem
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/3/14
 */
@AndroidEntryPoint
class MusicMoreBottomSheetFragment: BottomSheetDialogFragment()  {

    private var _binding: DialogMusicMoreBinding? = null
    private val binding get() = _binding!!

    private val musicMoreDialogViewModel by viewModels<MusicMoreDialogViewModel>()
    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    companion object{
        const val RESULT_PLAYLIST_MUSIC_DELETE = "result_playlistMusic_delete"
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = DialogMusicMoreBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        musicMoreDialogViewModel.mediaInfo.observe(viewLifecycleOwner, {
            if(it != null){
                updateMediaInfo(it)
            }
        })

        binding.containerAddToPlaylist.setOnClickListener {
            musicMoreDialogViewModel.mediaInfo.value?.let {
                mainActivityViewModel.addQueueItem(it.mediaId,it.parentId,MediaIDHelper.PLAYLIST_ADD_TYPE_LAST_PLAY)
                requireActivity().findViewById<TextView>(R.id.FluidMusicBottomBar).snackbar(
                    getString(R.string.description_add_to_playlist_info,it.mediaTitle), SNACKBAR_ALL_BOTTOM_BAR
                ).apply {
                }.show()
            }

            dismiss()
        }

        binding.containerAddNextToPlaylist.setOnClickListener {
            musicMoreDialogViewModel.mediaInfo.value?.let {
                mainActivityViewModel.addQueueItem(it.mediaId,it.parentId,MediaIDHelper.PLAYLIST_ADD_TYPE_NEXT_PLAY)
                requireActivity().findViewById<TextView>(R.id.FluidMusicBottomBar).snackbar(
                    getString(R.string.description_add_next_to_playlist_info,it.mediaTitle), SNACKBAR_ALL_BOTTOM_BAR
                ).apply {
                }.show()
            }

            dismiss()
        }

        binding.containerDeleteMusic.setOnClickListener {
            setFragmentResult(RESULT_PLAYLIST_MUSIC_DELETE, bundleOf(RESULT_PLAYLIST_MUSIC_DELETE to musicMoreDialogViewModel.mediaInfo.value))
            dismiss()
        }
    }

    private fun updateMediaInfo(mediaInfo: MoreInfoData) = with(binding){
        ivMusicImg.isVisible = mediaInfo.mediaArtUri != null
        containerAlbum.isVisible = !mediaInfo.isOffline && mediaInfo.albumId != null
        containerArtist.isVisible = !mediaInfo.isOffline && !mediaInfo.artists.isNullOrEmpty()
        containerDeleteMusic.isVisible = mediaInfo.inPlaylistShouldDelete && !mediaInfo.isOffline && !mediaInfo.id.isNullOrEmpty()
        tvMusicName.text = mediaInfo.mediaTitle
        tvMusicSubtitle.text = mediaInfo.mediaSubtitle
        Glide.with(ivMusicImg)
            .load(mediaInfo.mediaArtUri)
            .placeholder(R.drawable.img_default_album)
            .into(ivMusicImg)
        binding.containerAlbum.setOnClickListener {
            if(!mediaInfo.isOffline){
                if(mediaInfo.albumId != null){
                    findNavController().navigate(NavAlbumDirections.actionGlobalAlbumDetailFragment(mediaInfo.albumId))
                }
            }
        }
        binding.containerArtist.setOnClickListener {
            if(!mediaInfo.isOffline){
                if(!mediaInfo.artists.isNullOrEmpty()){
                    // 如果歌手有超过1个以上，则弹出弹窗问跳转到哪个歌手
                    if(mediaInfo.artists.size == 1){
                        findNavController().navigate(
                            NavArtistDirections.actionGlobalArtistDetailFragment(
                            mediaInfo.artists[0].id))
                    } else {
                        // 将歌手名展示在弹窗中，让用户选择
                        val artistNames = mediaInfo.artists.map {
                            it.artistName
                        }.toTypedArray()
                        MaterialAlertDialogBuilder(requireContext())
                            .setTitle(resources.getString(R.string.description_select_artist))
                            .setItems(artistNames) { _, which ->
                                findNavController().navigate(NavArtistDirections.actionGlobalArtistDetailFragment(
                                    mediaInfo.artists[which].id))
                            }
                            .show()
                    }

                }
            }
        }

        // 展示分享按钮
        binding.containerShareMusic.isVisible = mediaInfo.canShare
        binding.containerShareMusic.setOnClickListener {
            startActivity(Intent(requireContext(), AddMomentActivity::class.java).apply {
                putExtra("shareContent", MomentListItem.MomentShareItem(
                    mediaInfo.mediaId, MOMENT_SHARE_TYPE_MUSIC,mediaInfo.mediaTitle,mediaInfo.mediaSubtitle,
                    mediaInfo.mediaArtUri.toString()
                ))
            })
        }

        binding.containerCancel.setOnClickListener {
            dismiss()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}